var phoneCode;
var waitCode = 60;

$(function() {
  //监听val变化
  $(".log-item input").on('input propertychange focus', function() {
    var _this = $(this);
    if ($(this).val() != '') {
      setTimeout(function() {
        $(_this).siblings(".loginIcon").show();
      }, 200);
    } else {
      $(this).siblings(".loginIcon").removeAttr("style");
    }
  });
  $(".log-item input").on("blur", function() {
    var _this = $(this);
    setTimeout(function() {
      $(_this).siblings(".loginIcon").removeAttr("style");
    }, 200)
  });
  //清空输入框
  $(".log-item .loginIcon").on("click", function() {
    event.preventDefault();
    $(this).siblings("input").val('');
    $(this).hide();
  });

  getClinic(); // 获取诊所列表

});

$(document).keyup(function(event) {
  if (event.keyCode == 13) { //enter
    login();
  }
});
var pageUrl = window.location.search;
pageUrl = pageUrl.substring(9, pageUrl.length);

// 登录
function login() {
  var adminName = $('#adminName').val();
  var password = $('#password').val();
  if (adminName.trim().length == 0 || password.length == 0) {
    $('.log-error').html("用户名或密码不能为空");
    return false;
  }
  $.ajax({
    url: site.apiUrl + "/backManager/backUserLogin",
    type: "post",
    async: true,
    dataType: "JSON",
    ContentType: "application/json",
    data: {
      'tel': adminName,
      'password': password,
    },
    beforeSend: function(request) {
      request.setRequestHeader("headType", 1);
      request.setRequestHeader("ClientIdentity_MT", "_PC");
    },
    success: function(data) {
      console.log(data)
      if (data.code == 200) {
        window.localStorage.setItem("backstage-access-token", data.data.token);
        window.localStorage.setItem("backstage-access-userName", data.data.userName); // 姓名/昵称
        window.localStorage.setItem("backstage-access-adminName", data.data.telephone); // 登录账号
        window.localStorage.setItem("backstage-access-userId", data.data.id);
        window.localStorage.setItem("backstage-access-roleId", data.data.roleId);
        // var menuListArr = data.data.list; // 菜单集合
        // if (menuListArr.length > 1) {
        //   var lsMenuListArr = []
        //   for (var i = 0; i < menuListArr.length; i++) {
        //     menuListArr[i].url = site.interUrl + menuListArr[i].url
        //     lsMenuListArr.push(menuListArr[i])
        //   }
        //   window.localStorage.setItem("backstage-access-permissionList", JSON.stringify(data.data.list)); // 菜单
        // } else {
        //   window.location.href = site.interUrl + "login.html";
        // }
        if (pageUrl == '') {
          window.location.href = "index.html";
        } else {
          window.location.href = pageUrl;
        }
      } else {
        $('.log-error').html(data.msg);
      }
    },
    error: function(err) {
      console.log(err)
    }
  });
  // window.location.href = "index.html";
}

// 跳转忘记密码
function goForget() {
  $('.log-error').html("");
  $("#forget_password").show();
  $("#forget_tel").val('');
  $("#forget_code").val('');
  $("#forget_new_pass").val('');
  $("#forget_pass").val('');
  $("#login_box").hide();
}
// 跳转注册
function goRegister() {
  $('.log-error').html("");
  $("#clinic_select").val('');
  $("#register_ID").val('');
  $("#register_tel").val('');
  $("#register_code").val('');
  $("#register_new_pass").val('');
  $("#register_pass").val('');
  $("#register_box").show();
  $("#login_box").hide();
}

// 忘记密码-取消
function forgetCancel() {
  $('.log-error').html("");
  $("#forget_password").hide();
  $("#login_box").show();
}
// 注册-取消
function registerCancel() {
  $('.log-error').html("");
  $("#register_box").hide();
  $("#login_box").show();
}

// 获取诊所列表
function getClinic() {
  $.ajax({
    url: site.apiUrl + "/hospitalManager/selectMedicalHospitalInfoList",
    type: "get",
    dataType: "JSON",
    ContentType: "application/json",
    data: {
      page: 1,
      pageSize: 5000
    },
    beforeSend: function(request) {
      request.setRequestHeader("headType", 1);
      request.setRequestHeader("ClientIdentity_MT", "_PC");
    },
    success: function(f) {
      if (f.code == "success") {
        var forData = f.result.list;
        if (forData.length > 0) {
          for (var i = 0; i < forData.length; i++) {
            $("#clinic_select").append('<option value="'+ forData[i].id +'">'+ forData[i].hospitalName +'</option>');
          }
        }
      }
    },
    error: function(err) {
      console.log(err)
    }
  });
}

// 注册-提交
function registerSubmit() {
  var telephone = $('#register_tel').val();
  var password = $('#register_pass').val();
  var hospitalId = $('#clinic_select').val();
  var idCard = $('#register_ID').val();
  var register_new_pass = $('#register_new_pass').val();
  var register_code = $("#register_code").val();
  if (telephone.trim().length == 0 || password.length == 0) {
    $('.log-error').html("手机号或密码不能为空");
    return false;
  }
  // 验证所属诊所
  if (hospitalId == '') {
    $('.log-error').html("请选择一个诊所");
    return false;
  }
  // 验证验证码
  if (register_code != phoneCode) {
    $('.log-error').html("验证码有误，请重新输入");
    return false;
  }
  // 验证两次输入密码是否一致
  if (password != register_new_pass) {
    $('.log-error').html("确认新密码有误，请重新输入");
    return false;
  }
  $.ajax({
    url: site.apiUrl + "/backManager/doctorRegister",
    type: "post",
    async: true,
    dataType: "JSON",
    ContentType: "application/json",
    data: {
      'telephone': telephone,
      'password': password,
      'hospitalId': hospitalId,
      'idCard': idCard
    },
    beforeSend: function(request) {
      request.setRequestHeader("headType", 1);
      request.setRequestHeader("ClientIdentity_MT", "_PC");
    },
    success: function(data) {
      if (data.code == 200) {
        console.log('注册成功');
        layer.msg('注册成功');
        registerCancel(); // 显示登录框
      } else {
        $('.log-error').html(data.msg);
      }
    },
    error: function(err) {
      console.log(err)
    }
  });
}

// 忘记密码-提交
function forgetSubmit() {
  var tel = $('#forget_tel').val();
  var password = $('#forget_pass').val();
  var forget_new_pass = $('#forget_new_pass').val();
  var forget_code = $("#forget_code").val();
  if (tel.trim().length == 0 || password.length == 0) {
    $('.log-error').html("手机号或密码不能为空");
    return false;
  }
  // 验证验证码
  if (forget_code != phoneCode) {
    $('.log-error').html("验证码有误，请重新输入");
    return false;
  }
  // 验证两次输入密码是否一致
  if (password != forget_new_pass) {
    $('.log-error').html("确认新密码有误，请重新输入");
    return false;
  }
  $.ajax({
    url: site.apiUrl + "/backManager/backUserFindPwd",
    type: "post",
    async: true,
    dataType: "JSON",
    ContentType: "application/json",
    data: {
      'tel': tel,
      'password': password,
    },
    beforeSend: function(request) {
      request.setRequestHeader("headType", 1);
      request.setRequestHeader("ClientIdentity_MT", "_PC");
    },
    success: function(data) {
      if (data.code == 200) {
        console.log('修改成功');
        layer.msg('修改成功');
        forgetCancel(); // 显示登录框
      } else {
        $('.log-error').html(data.msg);
      }
    },
    error: function(err) {
      console.log(err)
    }
  });
}

// 获取验证码
function getCode(that, byId) {
  $(that).attr("disabled", true);
  var telephone = $(byId).val();
  var myreg = /^(13[0-9]|14[0-9]|15[0-9]|17[0-9]|18[0-9]|19[0-9])\d{8}$$/;

  if (myreg.test(telephone)) {
    $('.log-error').html('');
    $(that).text("验证码发送中");
    $.ajax({
      url: site.apiUrl + "/wechat/sendMessage",
      type: "get",
      dataType: "JSON",
      ContentType: "application/json",
      data: {
        'telephone': telephone
      },
      beforeSend: function(request) {
        request.setRequestHeader("headType", 1);
        request.setRequestHeader("ClientIdentity_MT", "_PC");
      },
      success: function(data) {
        if (data.code == 200) {
          phoneCode = data.data;
          $(that).removeAttr("disabled");
          $(that).text("获取验证码");
        } else {
          $('.log-error').html(data.msg);
          $(that).removeAttr("disabled");
          $(that).text("获取验证码");
        }
      },
      error: function(err) {
        console.log(err)
      }
    });
  } else {
    $('.log-error').html('请输入正确的手机号');
    $(that).removeAttr("disabled");
  }

}

// 验证码文本
function codeText(that) {
  if (waitCode == 0) {
    $(that).removeAttr("disabled");  
    $(that).text("获取验证码");
    waitCode = 60;
  } else {
    $(that).attr("disabled", true);
    $(that).text(waitCode + "s后重新获取");
    waitCode--;
    time = setTimeout(function() {
      codeText(that);
    }, 1000)
  }
}